<?php

namespace Yolo\Scheduler;

use function Swoole\Coroutine\go;

/**
 * 计划任务执行器
 */
class SchedulerRunner
{
    /**
     * @var AbstractScheduler[]
     */
    private array $schedulers = [];
    public function __construct()
    {
        $this->loadSchedulers();
    }

    /**
     * @return void
     */
    private function loadSchedulers(): void
    {
        $config = include BASE_PATH . '/config/config.php';
        if (isset($config['schedulers']) && is_array($config['schedulers'])) {
            foreach ($config['schedulers'] as $scheduler) {

                $schedulerInstance = new $scheduler();
                if ($schedulerInstance instanceof AbstractScheduler) {
                    $this->schedulers[] = $schedulerInstance;
                    echo "[INFO] Registered scheduler: {$schedulerInstance->getName()}\n";
                }
            }
        }

        if (empty($this->schedulers)) {
            echo "[INFO] No schedulers found\n";
        }
    }

    public function run(): void
    {
        foreach ($this->schedulers as $scheduler) {

            go(function () use ($scheduler) {
                $scheduler->start();
            });
        }

        echo "[INFO] Scheduler started.\n";
    }
}
